<?php

namespace app\wechat\controller;

use app\wechat\controller\Base;
use think\facade\Request;
use think\facade\View;
use think\facade\Db;
use think\facade\Log;
use helper\Wechat as WechatClass;
use EasyWeChat\Factory;
use app\admin\model\ucenter\Member as MemberModel;

class Wechat extends Base{
	protected $app;
	protected $Wechat;
	protected $config;
    public function initialize()
    {
        parent::initialize(); 
        $this->Wechat = new WechatClass();
        $this->config = $this->Wechat->get_config();
    	$this->config['oauth'] = [
    		'scopes'   => ['snsapi_userinfo'],
	        'callback' => request()->domain().url('wechat/wechat.wechat/getcode'),
    		];
        $this->app = Factory::officialAccount($this->config);
    }
    
    // 微信授权登录
	public function login(){
		$this->app->oauth->redirect()->send();
	}
	// 微信获取code
	public function getcode(){
		//回调地址会传回一个code，则我们根据code去获取openid和授权获取到的access_token
		$code = $_GET['code'];
		
		$user = $this->app->oauth->user();
		$user = $user->toArray();
		
		$memberinfo = MemberModel::where('wxopenid',$user['id'])->find();
		if(empty($memberinfo)){
            //首次进入，则获取用户信息，插入数据库
            $insert_data = [
                'wxopenid' => $user['id'],
				'wx_appid' => $this->config['app_id'],
                'username' => 'wx_'.uniqid(),
                'nickname' => $this->filterEmoji($user['nickname']),
                'avatar' => $user['avatar'],
                'province' => $user['original']['province'],
                'city' => $user['original']['city']
            ];
            $userId = MemberModel::insertGetId($insert_data);
            $memberinfo = MemberModel::where("id",$userId)->find();
        }
        $memberinfo = [
        	'id' => $memberinfo['id'],
        	'username' => $memberinfo['username'],
        	'nickname' => $memberinfo['nickname'],
        	'avatar' => $memberinfo['avatar'],
        	'wxopenid' => $memberinfo['wxopenid'],
        	];
        session('member',$memberinfo);
		header('Location:'. url('mobile/index/index')->domain(true));
	}
    public function filterEmoji($str)
	{
		$str = preg_replace_callback( '/./u',
		  function (array $match) {
			return strlen($match[0]) >= 4 ? '' : $match[0];
		  },
		  $str);
		return $str;
	}
    
    // 微信图文消息 文章详情
    public function info(){
        $id = $this->request->get('id');
        if(!$id){
            $this->error('无效的ID');
        }
        $info = Db::name('wx_news_article')->where('id',$id)->find();
        View::assign('info',$info);
        return '123';
    }
    
}